<?php
include "./index/control/IndexControl.php";
include "./index/libs/tag.class.php";
include "./index/libs/functions.php"; 
C("TPL_TAGS", "tag");

class HtmlControl extends Control {

    //生成首页
    function index() {
        C("debug", 0);
        ob_start();
        $control = new IndexControl;
        $control->index();
        $htmlData = ob_get_clean();
        if (file_put_contents("index.html", $htmlData)) {
            $this->success("首页生成成功");
        } else {
            $this->error("首页生成失败");
        }
    }

    //生成列表
    function cat() {
        $db = M("category");
        $cat = $db->field("cathtml,cid,archtml,catdir")->all();
        // p($cat);
        $control = new IndexControl;
        //生成目录
        foreach ($cat as $c) {
            $caturl = get_cat_url($c, 2);
            $path = dirname($caturl);
            is_dir($path) || dir_create($path);
            $_GET['cid'] = $c['cid'];
            ob_start();
            $control->cat();
            $data = ob_get_clean();
            file_put_contents($path . '/index.html', $data);
        }
    }

//生成文章
    function arc($id = null) {
        C("debug", 1);
        $db = K("arc");
        $where = $id ? " aid =$id" : "";
        $arcs = $db->where($where)->field("aid,cathtml,arc.cid,archtml,catdir")->all();
        $control = new IndexControl;
        //生成目录
        foreach ($arcs as $c) {
            $caturl = $this->getArcHtmPath($c);
            $path = dirname($caturl);

            is_dir($path) || dir_create($path);
            $_GET['aid'] = $c['aid'];
            ob_start();
            $control->arc();
            $data = ob_get_clean();
            file_put_contents($caturl, $data);
        }
    }

    /**
     * 获得静态文件存放路径
     * @param type $field
     * @return type
     */
    private function getArcHtmPath($field) {
        $date = getdate();
        $search = array(
            '{htmlpath}',
            '{catdir}',
            '{aid}',
            '{y}',
            '{m}',
            '{d}'
        );
        $replace = array(
            'h',
            $field['catdir'],
            $field['aid'],
            $date['year'],
            $date['mon'],
            $date['mday']
        );
        $path = str_replace($search, $replace, $field['archtml']);
        return PATH_ROOT . '/' . $path;
    }

}

?>
